﻿using System;
using System.Collections.Generic;
using System.Text;

namespace Workflows.Components.TextMining.Clustering
{
    /// <summary>
    /// 
    /// </summary>
    public class TermWeightCalculator
    {
        /// <summary>
        /// all shared term are treated equally, skipping any non-shared terms
        /// </summary>
        /// <param name="termCountInDoc1"></param>
        /// <param name="termCountInDoc2"></param>
        /// <param name="sharedTermCount"></param>
        /// <returns></returns>
        public static double TaminoCommonTermScale(int termCountInDoc1, int termCountInDoc2, int sharedTermCount)
        {
            double contributingTermScale = Math.Log10(termCountInDoc1 + termCountInDoc2);
            if (sharedTermCount > 0)
            {
                contributingTermScale =
                    Math.Log(
                        (double) (termCountInDoc1 + termCountInDoc2 - sharedTermCount)/
                        sharedTermCount, 2);
            }
            return contributingTermScale;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="docTermFreqs1"></param>
        /// <param name="docTermFreqs2"></param>
        /// <param name="termWeights"></param>
        /// <returns></returns>
        public static double TaminoWeightedTermScale(
            Dictionary<int,DocTermFreq> docTermFreqs1,
            Dictionary<int,DocTermFreq> docTermFreqs2,
            Dictionary<int,double> termWeights)
        {
            List<int> termIDs=new List<int>();
            foreach(int termID in docTermFreqs1.Keys)
            {
                termIDs.Add(termID);
            }
            foreach(int termID in docTermFreqs2.Keys)
            {
                if(!termIDs.Contains(termID))
                    termIDs.Add(termID);
            }
            double weightedSum = 0;
            double sharedWeight = 0;
            foreach(int termID in termIDs)
            {
                if (termWeights.ContainsKey(termID))
                    weightedSum += termWeights[termID];
                if (docTermFreqs1.ContainsKey(termID) && docTermFreqs2.ContainsKey(termID) && termWeights.ContainsKey(termID))
                    sharedWeight += termWeights[termID];
            }
            double contributingTermScale = 1;
            if(sharedWeight>0)
                contributingTermScale = Math.Log(weightedSum / sharedWeight, 2);
            
            return contributingTermScale;
        }
    }
}
